package com.warmlight.voicepacket.fragment.comm;

import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AbsListView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.squareup.otto.Subscribe;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.comm.FocusAdapter;
import com.warmlight.voicepacket.base.fragment.BaseFragment;
import com.warmlight.voicepacket.bean.comm.CommBean;
import com.warmlight.voicepacket.bean.comm.CommList;
import com.warmlight.voicepacket.common.OttoConstants;
import com.warmlight.voicepacket.contract.VideoContract;
import com.warmlight.voicepacket.db.SharedPerfenceConstant;
import com.warmlight.voicepacket.network.MapComm;
import com.warmlight.voicepacket.ottoEvent.CommRefreshBean;
import com.warmlight.voicepacket.ottoEvent.OVideoBean;
import com.warmlight.voicepacket.ottoEvent.OttoBus;
import com.warmlight.voicepacket.plugin.QmzbMediaManager;
import com.warmlight.voicepacket.plugin.QmzbVideoPlayer;
import com.warmlight.voicepacket.presenter.VideoPresenter;
import com.warmlight.voicepacket.ui.communitylm.widget.CommunityShare;
import com.warmlight.voicepacket.utils.Log;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by weiweijinpeng on 2018/9/10.
 * 视频
 */

public class VideoFragment extends BaseFragment implements  VideoContract.View,FocusAdapter.FocusItemListener {

    VideoContract.Presenter mPresenter;

    CommList commList;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;

    @BindView(R.id.comment_rl)
    RecyclerView mRecyclerView;

    LinearLayoutManager linearLayoutManager;

    FocusAdapter.FocusRecommViewHolder centerHolder;

    FocusAdapter.FocusRecommNormalViewHolder centerNormalHolder;

    FocusAdapter focusAdapter;

    PlayHandler playHandler;

    int currentPosition=0;

    int page;

    int pageSize=8;

    int likePosition;

    private int isLike;

    int likeCommPosition;

    private int isCommLike;

    String typeClick;//点赞的类型

    String mType;

    boolean onResumeoFist=false;//判断是否第一进入onResum，如果第二次直接播放上次跳走的位置视频

    // 标志位，标志已经初始化完成。
    private boolean isPrepared;

    int detailsClickIs_Like;//详情页的点赞的数量


    @Override
    public void onStart() {
        super.onStart();
        //注册到bus事件总线中
        OttoBus.getInstance().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        OttoBus.getInstance().unregister(this);
    }

    // 接受事件
    @Subscribe
    public void setContent(OVideoBean data) {
        if (data.getType().equals(OttoConstants.COMMPLAY)){
            playVideo(playVideoss());
            return;
        }
        //详情页点赞
        if (data.getType().equals(OttoConstants.COMMCLICK)){

            for (int i=0;i<focusAdapter.getData().size();i++){
                if (focusAdapter.getData().get(i).getId().equals(data.getItemId())){

                    detailsClickIs_Like=mSharePreferenceUtil.getInt(SharedPerfenceConstant.DEATILSLIKECLICK);
                    if (focusAdapter.getData().get(i).getIs_like()==detailsClickIs_Like){
                        return;
                    }
                    commListLike(i,detailsClickIs_Like);
                    break;
                }
            }

            return;
        }

        //详情页神评点赞
        if (data.getType().equals(OttoConstants.COMMGODCLICK)){

            for (int i=0;i<focusAdapter.getData().size();i++){
                if (focusAdapter.getData().get(i).getId().equals(data.getItemId())){

                    detailsClickIs_Like=mSharePreferenceUtil.getInt(SharedPerfenceConstant.DEATILSLIKECLICK);
                    if (focusAdapter.getData().get(i).getGod_info().getIs_like()==detailsClickIs_Like){
                        return;
                    }
                    commLike(i,detailsClickIs_Like);
                    break;
                }
            }

            return;
        }
        //详情页评论
        if (data.getType().equals(OttoConstants.COMMCOMM)){

            for (int i=0;i<focusAdapter.getData().size();i++){
                if (focusAdapter.getData().get(i).getId().equals(data.getItemId())){

                    focusAdapter.getData().get(i).setComment_num(mSharePreferenceUtil.getString(SharedPerfenceConstant.DEATILSCOMMCLICK));

                    focusAdapter.isLike(likePosition);
                    break;
                }
            }
            return;
        }
        smartRefreshLayout.autoRefresh();
        OttoBus.getInstance().post(new CommRefreshBean(OttoConstants.COMMREFRESH));
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_video;
    }

    @Override
    public void initViews() {
        playHandler=new PlayHandler();

        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                setData(false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                setData(true);
            }
        });

        focusAdapter = new FocusAdapter(getActivity(),this,"video");

        linearLayoutManager = new LinearLayoutManager(getActivity());

        mRecyclerView.setLayoutManager(linearLayoutManager);

        mRecyclerView.setAdapter(focusAdapter);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        playVideo();
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    public void initData() {
        isPrepared = true;
        lazyLoad();
    }

    /**
     * 懒加载
     */
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        isPrepared = false;
        OttoBus.getInstance().post(new CommRefreshBean(OttoConstants.COMMREFRESH));
        setData(true);

    }

    public void setData(boolean isRefresh){

        if (isRefresh){
            page = 1;
        }else{
            page ++;
        }

        MapComm mapComm=new MapComm();
        mapComm.put("page",String.valueOf(page));
        mapComm.put("pagesize",String.valueOf(pageSize));
        mapComm.put("type","2");
        getPresenter().getVideoList(MapComm.getMap());
    }


    @Override
    public VideoContract.Presenter getPresenter() {
        if (mPresenter==null){
            mPresenter=new VideoPresenter(this,getActivity());
        }
        return mPresenter;
    }

    @Override
    public void setPresenter(VideoContract.Presenter presenter) {

    }

    @Override
    public void onVideoList(CommBean list) {
        OttoBus.getInstance().post(new CommRefreshBean(OttoConstants.COMMSTOP));
        if (page == 1){
            focusAdapter.setData(list.getList());
            if (list.getList().size() == 0){
                smartRefreshLayout.setNoMoreData(true);
            }
            playMedia();
        }else {
            focusAdapter.addData(list.getList());
            if (list.getList().size() == 0){
                smartRefreshLayout.setNoMoreData(true);
            }
        }
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();

    }
    private void playMedia(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Message message=new Message();
                message.what=0;
                playHandler.handleMessage(message);
            }
        },200);
    }

    /**
     * 播放视频
     */
    private void playVideo() {

        if (currentPosition == playVideoss()) {
            return;
        }
        playVideo(playVideoss());
    }


    /**
     * 播放视频
     */
    private void playVideo(int firstPosition) {

        currentPosition = firstPosition;

        //视频页
        if (focusAdapter.getItemCount() > currentPosition && focusAdapter.getItemCount() != 0)
            commList = focusAdapter.getData().get(currentPosition);
        View childAt = linearLayoutManager.findViewByPosition(currentPosition);


        focusAdapter.videoPreppare(childAt,currentPosition);
    }

    private class PlayHandler extends Handler{

        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    playVideo(0);
                    break;
            }
        }
    }

    @Override
    public void onVideoFailure() {

    }

    @Override
    public void onVideoNoMore() {

    }

    @Override
    public void onNoNetWork() {

    }

    @Override
    public void isLikeClick(int position,String type,String clickType) {

        typeClick=clickType;
        likeCommPosition=position;

        likePosition=position;
        mType=type;
        isLike=focusAdapter.getData().get(position).getIs_like();
        int count= isLike==0 ? 1 : 2;

        MapComm mapComm=new MapComm();
        mapComm.put("id",focusAdapter.getData().get(position).getId());
        mapComm.put("type","1");
        mapComm.put("status",String.valueOf(count));
        getPresenter().getLikeList(MapComm.getMap());


    }

    @Override
    public void isLikeCommClick(int position, String type, String clickType) {
        typeClick=clickType;
        likeCommPosition=position;
        mType=type;
        isCommLike=focusAdapter.getData().get(position).getGod_info().getIs_like();
        int count= isCommLike==0 ? 1 : 2;

        MapComm mapComm=new MapComm();
        mapComm.put("id",focusAdapter.getData().get(position).getGod_info().getId());
        mapComm.put("type","2");
        mapComm.put("status",String.valueOf(count));
        getPresenter().getLikeList(MapComm.getMap());

    }



    @Override
    public void onLikeList(String list) {

        if (list.toString().equals("成功")){

            if (typeClick.equals("comm")){
                isCommLike=isCommLike==0 ? 1 : 0;

                commLike(likeCommPosition,isCommLike);
                return;
            }

            isLike=isLike==0 ? 1 : 0;

            commListLike(likePosition,isLike);
        }
    }

    /**
     * 神评点赞
     */
    private void commLike(int likeCommPosition,int isCommLike){
        commList = focusAdapter.getData().get(likeCommPosition);

        int count= isCommLike==0 ? -1 : 1;

        focusAdapter.getData().get(likeCommPosition).getGod_info().setIs_like(isCommLike);

        String likenum = focusAdapter.getData().get(likeCommPosition).getGod_info().getLike_num();

        if (!likenum.contains("k") && !likenum.contains("w")) {
            int resetCount = Integer.valueOf(focusAdapter.getData().get(likeCommPosition).getGod_info().getLike_num());

            focusAdapter.getData().get(likeCommPosition).getGod_info().setLike_num(String.valueOf(resetCount + count));
        }

        focusAdapter.isLike(likeCommPosition);
    }

    /**
     * 列表点赞,与详情页的点赞返回时数据同步进行方法重载
     */
    private void commListLike(int likePosition,int isLike){
        commList = focusAdapter.getData().get(likePosition);

        int count= isLike==0 ? -1 : 1;

        String like_num = commList.getLike_num();

        if (!like_num.contains("k") && !like_num.contains("w")) {

            int resetCount = Integer.valueOf(commList.getLike_num());

            commList.setLike_num(String.valueOf(resetCount + count));
        }

        commList.setIs_like(isLike);

        focusAdapter.isLike(likePosition);
    }




    /**
     * 获取当前viewke可见的索引
     * @return
     */
    public int playVideoss() {
        int firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
        int currentIndex = firstVisibleItem;
        int lastHeight = 0;
        for (int i = firstVisibleItem; i <= lastVisibleItem; i++) {
            View view = linearLayoutManager.getChildAt(i - firstVisibleItem);
            if (null == view) {
                continue;
            }
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            Rect localRect = new Rect();
            view.getLocalVisibleRect(localRect);
            int showHeight = localRect.bottom - localRect.top;
            if (showHeight > lastHeight) {
                currentIndex = i;
                if (currentIndex < 0) {
                    currentIndex = 0;
                }
                lastHeight = showHeight;

            }
        }
        return currentIndex;
    }

    @Override
    public void shareClick(int position) {

        Map<String,String> map=new HashMap<>();
        map.put("title",focusAdapter.getData().get(position).getShare().getTitle());
        map.put("msc",focusAdapter.getData().get(position).getShare().getDesc());
        map.put("url",focusAdapter.getData().get(position).getShare().getH5_url());
        map.put("img",focusAdapter.getData().get(position).getShare().getPic_url());
        map.put("type","1");
        map.put("id",focusAdapter.getData().get(position).getId());
        CommunityShare.getInstance(map).show(getChildFragmentManager().beginTransaction()
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE),"ads");

    }


    @Override
    public void onResume() {
        super.onResume();
        //这里根据滑动的tab位置，来判断是哪一个tab来进行播放

        if (mSharePreferenceUtil.getInt(SharedPerfenceConstant.COMMTABTYPE)==1){
            if (onResumeoFist)
                playVideo(playVideoss());
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        onResumeoFist=true;
        QmzbVideoPlayer.onPlayOnPause();
    }

}
